<html><head><meta charset="utf-8"><title>46 ServerSocket 源码及面试题   -慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">


<div class="main-con hide-menu">
    <!-- 左侧菜单 & 索引 -->
    
    <div class="right-content" style="padding-left: 0px;">
        <div class="container clearfix" id="top" style="width: 1134px; display: block;">
            
            
            <div class="center_con js-center_con l" style="width: 1134px;">
                <div class="article-con">
                                            <!-- 买过的阅读 -->
                        

                    
                    <div class="art-title" style="margin-top: 0px;">
                        46 ServerSocket 源码及面试题   
                    </div>
                    <div class="art-info clearfix">
                        
                        <span class="l">
                            更新时间：2019-12-02 09:48:40
                        </span>
                    </div>
                    <div class="art-top">
                                                <img src="https://img3.mukewang.com/5de079a40001eafb06400359.jpg" alt="">
                                                                        <div class="famous-word-box">
                            <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                            <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                            <div class="famous-word">既然我已经踏上这条道路，那么，任何东西都不应妨碍我沿着这条路走下去。<p class="author">——康德</p></div>
                        </div>
                                            </div>
                    <div class="art-content js-lookimg">
                        <div id="article_content">
                            <div class="cl-preview-section"><h2 id="引导语" style="font-size: 30px;">引导语</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">上一小节我们学习了 Socket，本文我们来看看服务端套接字 API：ServerSocket，本文学习完毕之后，我们就可以把客服端 Socket 和服务端 ServerSocket 串联起来，做一个真实的网络通信的 demo 了。</p>
</div><div class="cl-preview-section"><h2 id="类属性" style="font-size: 30px;">1 类属性</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">ServerSocket 的主要作用，是作为服务端的套接字，接受客户端套接字传递过来的信息，并把响应回传给客户端，其属性非常简单，如下：</p>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">private</span> <span class="token keyword">boolean</span> created <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span><span class="token comment">// 已创建</span>
<span class="token keyword">private</span> <span class="token keyword">boolean</span> bound <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span><span class="token comment">// 绑定</span>
<span class="token keyword">private</span> <span class="token keyword">boolean</span> closed <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span><span class="token comment">// 已关闭</span>
<span class="token comment">// 底层的功能都依靠 SocketImpl 来实现</span>
<span class="token keyword">private</span> SocketImpl impl<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">ServerSocket 和 Socket 一样，底层都是依靠 SocketImpl 的能力，而 SocketImpl 底层能力的实现基本上都是 native 方法实现的。</p>
</div><div class="cl-preview-section"><h2 id="初始化" style="font-size: 30px;">2 初始化</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">初始化大概可以分成两类：无参构造器和有参构造器。</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">无参构造器做的事情比较简单，只指定了 SocketImpl 为 SocksSocketImpl 类；</li>
<li style="font-size: 20px; line-height: 38px;">有参构造器有几种初始化的形式，我们一起来看一下参数最多的构造器的源码。</li>
</ol>
</div><div class="cl-preview-section"><pre class="  language-java"><code class="prism  language-java"><span class="token keyword">public</span> <span class="token function">ServerSocket</span><span class="token punctuation">(</span><span class="token keyword">int</span> port<span class="token punctuation">,</span> <span class="token keyword">int</span> backlog<span class="token punctuation">,</span> InetAddress bindAddr<span class="token punctuation">)</span> <span class="token keyword">throws</span> IOException <span class="token punctuation">{</span>
    <span class="token comment">// 默认是 SocksSocketImpl 实现</span>
    <span class="token function">setImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 端口必须大于 0，小于 65535</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>port <span class="token operator">&lt;</span> <span class="token number">0</span> <span class="token operator">||</span> port <span class="token operator">&gt;</span> <span class="token number">0xFFFF</span><span class="token punctuation">)</span>
        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">IllegalArgumentException</span><span class="token punctuation">(</span>
                   <span class="token string">"Port value out of range: "</span> <span class="token operator">+</span> port<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment">// 最大可连接数如果小于1，那么采取默认的 50</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>backlog <span class="token operator">&lt;</span> <span class="token number">1</span><span class="token punctuation">)</span>
      backlog <span class="token operator">=</span> <span class="token number">50</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
        <span class="token comment">// 底层 navtive 方法</span>
        <span class="token function">bind</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">InetSocketAddress</span><span class="token punctuation">(</span>bindAddr<span class="token punctuation">,</span> port<span class="token punctuation">)</span><span class="token punctuation">,</span> backlog<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span><span class="token punctuation">(</span>SecurityException e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
    <span class="token punctuation">}</span> <span class="token keyword">catch</span><span class="token punctuation">(</span>IOException e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">throw</span> e<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">入参 port 指的是 ServerSocket 需要绑定本地那个端口。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">入参 backlog 指的是服务端接受客户端连接队列的最大长度，这里需要注意的是，这里并不是限制客户端连接的个数，我们在 JDK8 版本下做过实验，我们把服务端的 backlog 设置成 1，并且变慢服务端的处理速度，当服务端并发请求过来时，并不是第二个请求过来就拒绝连接，我们在实际工作中，最好也不要用 backlog 来限制客户端连接的个数。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">还有点需要注意的是 backlog 小于 1 时，backlog 会被设置成默认的 50。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">入参 InetAddress 表示 ip 地址。</p>
</div><div class="cl-preview-section"><h2 id="bind" style="font-size: 30px;">3 bind</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">bind 方法主要作用是把 ServerSocket 绑定到本地的端口上，只有当我们使用无参构造器初始化 ServerSocket 时，才会用到这个方法，如果使用有参构造器的话，在初始化时就已经绑定到本地的端口上了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">配合无参构造器，一般我们这么用：</p>
</div><div class="cl-preview-section"><pre><code>// 进行初始化
ServerSocket serverSocket = new ServerSocket();
// 进行绑定
serverSocket.bind(new InetSocketAddress("localhost", 7007));
</code></pre>
</div><div class="cl-preview-section"><h2 id="accept" style="font-size: 30px;">4 accept</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">accept 方法主要是用来 ServerSocket 接受来自客户端的套接字的，如果此时没有来自客户端的请求时，该方法就会一直阻塞，如果有通过 setSoTimeout 方法设置超时时间，那么 accept 只会在超时间内阻塞，过了超时时间就会抛出异常。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">bind 和 accept 方法底层都是 native 方法实现，我们就不看源码了。</p>
</div><div class="cl-preview-section"><h2 id="面试题" style="font-size: 30px;">5 面试题</h2>
</div><div class="cl-preview-section"><h3 id="说说你对-socket-和-serversocket-的理解？">5.1 说说你对 Socket 和 ServerSocket 的理解？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：两者我们都可以称为套接字，底层基于 TCP/UDP 协议，套接字对底层协议进行了封装，让我们使用时更加方便，Socket  常被使用在客户端，用于向服务端请求数据和接受响应，ServerSocket  常用于在服务端，用于接受客户端的请求并进行处理，两者其底层使用都是依靠 SocketImpl 的子类的 native 方法。</p>
</div><div class="cl-preview-section"><h3 id="说说对-socketoptions-中的-so_timeout-的理解？">5.2 说说对 SocketOptions 中的 SO_TIMEOUT 的理解？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：SocketOptions 类有很多属性设置，比如 SO_TIMEOUT 、SO_LINGER 等等，这些问题说一下自己的理解即可，可以参考 《Socket 源码及面试题》 中对各种属性的解析。</p>
</div><div class="cl-preview-section"><h3 id="在构造-socket-的时候，我可以选择-tcp-或-udp-么？应该如何选择？">5.3 在构造 Socket 的时候，我可以选择 TCP 或 UDP 么？应该如何选择？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：可以的，Socket  有三个参数的构造器，第三个参数表示你想使用 TCP 还是 UDP。</p>
</div><div class="cl-preview-section"><h3 id="tcp-有自动检测服务端是否存活的机制么？有没有更好的办法？">5.4 TCP 有自动检测服务端是否存活的机制么？有没有更好的办法？</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">答：有的，我们可以通过 setKeepAlive 方法来激活该功能，如果两小时内，客户端和服务端的套接字之间没有任何通信，TCP 会自动发送 keepalive 探测给服务端，预测服务端有三种情况：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">服务端使用预期的 ACK 回复，说明一切正常；</li>
<li style="font-size: 20px; line-height: 38px;">服务端回复 RST，表示服务端处于死机或者重启状态，终止连接；</li>
<li style="font-size: 20px; line-height: 38px;">没有得到服务端的响应（会尝试多次），表示套接字已经关闭了。</li>
</ol>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">但我们并不建议使用这种方式，我们可以自己起一个定时任务，定时的访问服务端的特殊接口，如果服务端返回的数据和预期一致，说明服务端是存活的。</p>
</div><div class="cl-preview-section"><h2 id="总结" style="font-size: 30px;">总结</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Socket 和 ServerSocket 在源码方面没啥特别可说的地方，基本都是一些设置，底层实现都是 native 的方法，但面试官会从此延伸到一些网络协议方面的知识，因为这已经超出本专栏的范畴了，感兴趣的同学可以自行百度。</p>
</div>}
                        </div>
                    </div>
                                            <!-- 买过的阅读 -->
                        <div class="art-next-prev clearfix">
                                                                                                <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/887">
                                                                    <div class="prev l clearfix">
                                        <div class="icon l">
                                            <i class="imv2-arrow3_l"></i>
                                        </div>
                                        <p>
                                            45 Socket 源码及面试题  
                                        </p>
                                    </div>
                                </a>
                                                                                                                            <!-- 已买且开放 或者可以试读 -->
                                    <a href="/read/47/article/889">
                                                                    <div class="next r clearfix">
                                        <p>
                                            47 工作实战：Socket 结合线程池的使用 
                                        </p>
                                        <div class="icon r">
                                            <i class="imv2-arrow3_r"></i>
                                        </div>

                                    </div>
                                </a>
                                                    </div>
                                    </div>
                <div class="comments-con js-comments-con" id="coments_con">
                </div>

                
            </div>
            
            
            

        </div>
    </div>
</div>

<div class="modal modal-jiaQun-new hide" id="modal-jiaQun">
    <div class="inner" style="">
        <div class="modal-close js-close-jiaQun">
            <i class="imv2-close"></i>
        </div>
        <div class="content">
            <img src="https://img4.mukewang.com/5d634d40000119e505400602.jpg">
            <div class="right-info">
                <div class="title">
                    扫码加入慕课Java核心用户群
                </div>
                <div class="desc">
                                            <p class="mb6">验证信息：<span id="joincode">1909271435058473</span><span class="copy js-copy-joincode">复制</span></p>
                                        <p class="mb6">QQ讨论群号：906691736</p>
                                            <p>QQ群URL：<a href="https://jq.qq.com/?_wv=1027&amp;k=55RtSbJ" target="_blank">点击访问</a></p>
                                    </div>
            </div>
            <p class="tip">若遇到搜索不到QQ群或加群失败，请联系客服邮箱:kf@imooc.com</p>
        </div>
    </div>
</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>